package com.jzo2o.orders.base.handler;

import cn.hutool.db.DbRuntimeException;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.model.dto.OrderSnapshotDTO;
import com.jzo2o.orders.base.model.dto.OrderUpdateStatusDTO;
import com.jzo2o.orders.base.service.IOrdersCommonService;
import com.jzo2o.statemachine.core.StatusChangeEvent;
import com.jzo2o.statemachine.core.StatusChangeHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author wys
 * @version V1.0
 * @date 2025-04-06 10:01
 */
@Slf4j
@Component("order_payed")
public class OrderPayedHandler implements StatusChangeHandler<OrderSnapshotDTO> {
    @Resource
    private IOrdersCommonService ordersCommonService;
    @Override
    public void handler(String bizId, StatusChangeEvent statusChangeEventEnum, OrderSnapshotDTO bizSnapshot) {
        log.info("支付成功事件处理逻辑开始，订单号：{}", bizId);
        OrderUpdateStatusDTO orderUpdateStatusDTO = new OrderUpdateStatusDTO();
        orderUpdateStatusDTO.setId(bizSnapshot.getId());
        orderUpdateStatusDTO.setOriginStatus(OrderStatusEnum.NO_PAY.getStatus());
        orderUpdateStatusDTO.setTargetStatus(OrderStatusEnum.DISPATCHING.getStatus());
        orderUpdateStatusDTO.setPayStatus(bizSnapshot.getPayStatus());
        orderUpdateStatusDTO.setPayTime(bizSnapshot.getPayTime());
        orderUpdateStatusDTO.setTradingOrderNo(bizSnapshot.getTradingOrderNo());
        orderUpdateStatusDTO.setTransactionId(bizSnapshot.getThirdOrderId());
        orderUpdateStatusDTO.setTradingChannel(bizSnapshot.getTradingChannel());
        Integer result = ordersCommonService.updateStatus(orderUpdateStatusDTO);
        if (result <= 0) {
            throw new DbRuntimeException("支付成功事件处理失败");
        }
    }
}
